from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from rest_framework_jwt.settings import api_settings
from menu.models import SysMenu, SysMenuSerializer
from role.models import SysRole
from user.models import SysUser, SysUserSerializer
import json
from django.core.paginator import Paginator
from cmdb import settings
from datetime import datetime
from datacenter.models import Datacenter,SysDacenterSerializer
from datacenter.models import Ract,SysRactSerializer,SysCenterRact

from utils.idcract import DataCenterVisualizer
from utils.idcract import DataCenterVisualizerwj
import mpld3
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle, Polygon
from matplotlib.font_manager import FontProperties
from matplotlib.legend import Legend
import matplotlib.patheffects as patheffects

class StatusView(View):

    def post(self, request):
        data = json.loads(request.body.decode("utf-8"))
        id = data['id']
        status = data['status']
        user_object = Ract.objects.get(id=id)
        user_object.status = status
        user_object.save()
        return JsonResponse({'code': 200})

class ActionView(View):

    def get(self, request):
        """
        根据id获取角色信息
        :param request:
        :return:
        """
        id = request.GET.get("id")
        role_object = Datacenter.objects.get(id=id)
        return JsonResponse({'code': 200, 'role': SysDacenterSerializer(role_object).data})

    def delete(self, request):
        """
        删除操作
        :param request:
        :return:
        """
        idList = json.loads(request.body.decode("utf-8"))
        Datacenter.objects.filter(role_id__in=idList).delete()
        Ract.objects.filter(role_id__in=idList).delete()
        SysRole.objects.filter(id__in=idList).delete()
        return JsonResponse({'code': 200})

class GrantRact(View):

    def post(self, request):
        data = json.loads(request.body.decode("utf-8"))
        user_id = data['id']
        roleIdList = data['roleIds']
        print ("66666")
        print(user_id, roleIdList)
        SysCenterRact.objects.filter(ract_id=user_id).delete()  # 删除用户角色关联表中的指定用户数据
        for roleId in roleIdList:
            userRole = SysCenterRact(ract_id=user_id, center_id=roleId)
            print ("1234567")
            userRole.save()
        return JsonResponse({'code': 200})
class IdcView(View):
    def get(self, request):
        id=1
        role_object = Ract.objects.filter(
            id__in=SysCenterRact.objects.filter(center_id=id).values('ract_id')
        )
        print ("3333333333")
        print (role_object)
        print ("33333333333")
        visualizer = DataCenterVisualizer()
        visualizer.add_wall([(0, 0), (80, 0), (80, 180), (0, 180)])
        visualizer.add_door((80, 150), width=5)
        for i in SysRactSerializer(role_object,many=True).data:
            visualizer.add_rack(i["name"],eval(i["position"]),status=i["status"])


       #visualizer.add_rack("N9", (50, 12))
        #visualizer.add_rack(aa["name"],tuple((aa['position'].split(','))),status=aa["status"])
        fig = visualizer.plot_layout()
        plt.savefig('/root/test/cmdb1/cmdb/static/idc/rack_status.png', dpi=360, bbox_inches='tight')
        plt.show()

        #count = Ract.objects.filter(status='available').count()
        count = Ract.objects.filter(
            id__in=SysCenterRact.objects.filter(center_id=id).values('ract_id')
        ).filter(status='available').count()
        print ("55555")
        print (count)
        return render(request, 'rack_status.html',{'count': count})

class IdcViewwj(View):
    def get(self, request):
        id=2
        role_object = Ract.objects.filter(
            id__in=SysCenterRact.objects.filter(center_id=id).values('ract_id')
        )

        visualizer = DataCenterVisualizerwj()
        visualizer.add_wall([(0, 0), (80, 0), (80, 180), (0, 180)])
        visualizer.add_door((80, 150), width=5)
        for i in SysRactSerializer(role_object,many=True).data:
            visualizer.add_rack(i["name"],eval(i["position"]),status=i["status"])

        fig = visualizer.plot_layout()
        plt.savefig('/root/test/cmdb1/cmdb/static/idc/rack_status.png', dpi=360, bbox_inches='tight')
        plt.show()

        count = Ract.objects.filter(
            id__in=SysCenterRact.objects.filter(center_id=id).values('ract_id')
        ).filter(status='available').count()
        return render(request, 'rack_status.html',{'count': count})


class ListAllView(View):

    def get(self, request):
        obj_datacenterList = Datacenter.objects.all().values()  # 转成字典
        roleList = list(obj_datacenterList)  # 把外层的容器转为List
        print ("777")
        return JsonResponse(
            {'code': 200, 'roleList': roleList})
class SearchView(View):

    def post(self, request):
        data = json.loads(request.body.decode("utf-8"))
        pageNum = data['pageNum']  # 当前页
        pageSize = data['pageSize']  # 每页大小
        query = data['query']  # 查询参数
        print(pageSize, pageNum)
        roleListPage = Paginator(Datacenter.objects.filter(name__icontains=query), pageSize).page(pageNum)
        obj_roles = roleListPage.object_list.values()  # 转成字典
        roles = list(obj_roles)  # 把外层的容器转为List
        total = Datacenter.objects.filter(name__icontains=query).count()
        return JsonResponse({'code': 200, 'roleList': roles, 'total': total})
        # return JsonResponse(
        #     {'code': 200, 'roleList': roles, 'total': total})
class ActionView(View):
    def get(self, request):
        """
        根据id获取用户信息
        :param request:
        :return:
        """
        id = request.GET.get("id")
        user_object = Ract.objects.get(id=id)
        return JsonResponse({'code': 200, 'user': SysRactSerializer(user_object).data})

    def delete(self, request):
        """
        删除操作
        :param request:
        :return:
        """
        idList = json.loads(request.body.decode("utf-8"))
        print (idList)
        print ("333333")
        SysCenterRact.objects.filter(ract_id__in=idList).delete()
        Ract.objects.filter(id__in=idList).delete()
        print ("33333")
        return JsonResponse({'code': 200})

class ActionViewIdc(View):

    def get(self, request):
        """
        根据id获取用户信息
        :param request:
        :return:
        """
        id = request.GET.get("id")
        user_object = Datacenter.objects.get(id=id)
        return JsonResponse({'code': 200, 'user': SysDacenterSerializer(user_object).data})
class SearchRactView(View):
    def post(self, request):
        data = json.loads(request.body.decode("utf-8"))
        pageNum = data['pageNum']  # 当前页
        pageSize = data['pageSize']  # 每页大小
        query = data['query']  # 查询参数
        print(pageSize, pageNum,query)
        roleListPage = Paginator(Ract.objects.filter(name__icontains=query), pageSize).page(pageNum)
        obj_roles = roleListPage.object_list.values()  # 转成字典
        roles = list(obj_roles)  # 把外层的容器转为List
        total = Ract.objects.filter(name__icontains=query).count()
        users = list(obj_roles)  # 把外层的容器转成List
        for user in users:
            userId = user['id']
            roleList = Datacenter.objects.raw(
                "SELECT id,NAME FROM sys_datacenter WHERE id IN (SELECT center_id FROM sys_cen_ract WHERE ract_id=" + str(
                    userId) + ")")
            roleListDict = []
            for role in roleList:
                roleDict = {}
                roleDict["id"] = role.id
                roleDict["name"] = role.name
                roleListDict.append(roleDict)
            user['roleList'] = roleListDict
        total = Ract.objects.filter(name__icontains=query).count()
        print(total)
        print("788888")
        print(users)
        return JsonResponse({'code': 200, 'roleList': users, 'total': total})
    #    return JsonResponse(
    #        {'code': 200, 'roleList': roles, 'total': total})
class SaveView(View):
    def post(self, request):
        data = json.loads(request.body.decode("utf-8"))
        if data['id'] == -1:  # 添加
            obj_sysUser = Ract(name=data['name'], position=data['position'],
                                  status=data['status'],
                                  remark=data['remark'])
            obj_sysUser.save()
        else:  # 修改
            obj_sysUser = Ract(id=data['id'], name=data['name'],
                                  status=data['status'],remark=data['remark'],
                                   position=data['position'],create_time=data['create_time'])
            obj_sysUser.create_time = datetime.now().date()

            obj_sysUser.save()
        return JsonResponse({'code': 200})
